package com.lz.service.smsmail.juhe;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.lz.rabbitmq.common.RabbitMqConstants;
import com.lz.service.smsmail.Init;
import com.lz.service.smsmail.common.Config;

@Component
public class JuHeSms {

	private static final Logger LOG = LoggerFactory.getLogger(JuHeSms.class);
	private static final Gson GSON = new Gson();
	
	@Autowired
	private RestTemplate restTemplate;
	/**
	 * 发送短信
	 * @param mobile	手机号码
	 * @param tpl_id	短信模板ID
	 * @param tpl_value	变量名和变量值对
	 * @return
	 */
	public JuHeSmsResult send(String mobile, String tpl_id, String tpl_value){
		String url = "";
		try {
			url = Config.JUHE_SMS_SEND_URL + "?mobile=" + mobile + "&key=" + Config.JUHE_APPKEY + "&tpl_id=" + tpl_id
					+ "&tpl_value=" + URLEncoder.encode(tpl_value + "", "UTF-8");
			LOG.info("sms Send url={}", url);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
		JuHeSmsResult juHeSmsResult = restTemplate.getForObject(url, JuHeSmsResult.class);
		LOG.info("juHeSmsResult={}", juHeSmsResult);
		juHeSmsResult.setMobile(mobile);
		juHeSmsResult.setTpl_id(tpl_id);
		juHeSmsResult.setTpl_value(tpl_value);
		juHeSmsResult.setSend_time(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		if(Config.JUHE_SMS_LOG_SWITCH == 1){
			try {
				Init.rabbitMqLogProducer.sendMessage(RabbitMqConstants.ROUTING_KEY_LZMH_JUHE_SMS_LOG, GSON.toJson(juHeSmsResult));
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error("Exception={}", ExceptionUtils.getFullStackTrace(e));
			}
		}
		return juHeSmsResult;
	}
}
